package com.yijiue.ace.discovery.predicate;

import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
import com.yijiue.ace.core.InMemoryAce;
import com.yijiue.ace.core.model.AceGray;
import org.springframework.util.StringUtils;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 灰度规则实现
 *
 * @author YIJIUE
 */
public class MetadataAwarePredicate extends DiscoveryEnabledPredicate {

    public static Map<String, AtomicLong> map = new ConcurrentHashMap<>();

    /**
     * 匹配规则
     *
     * @param server the discovered server
     * @return true | false
     */
    @Override
    protected boolean apply(DiscoveryEnabledServer server) {
        final Map<String, String> metaInfo = server.getInstanceInfo().getMetadata();
        final String appName = server.getMetaInfo().getAppName();

        AceGray aceGray = InMemoryAce.aceGrayMap.get(appName.toLowerCase());
        if (aceGray == null) {
            return true;
        }
        // 为每一个灰度服务创建一个计数器
        AtomicLong atomicLong = map.get(appName.toLowerCase());
        if (atomicLong != null) {
            String gray = metaInfo.get(aceGray.getMetadataKey());
            String metadataValue = aceGray.getMetadataValue();
            int routingRatio = aceGray.getRoutingRatio();
            // 如果是灰度服务则进行路由 否则 路由到正常的机器
            if (!StringUtils.isEmpty(gray) && gray.equals(metadataValue) && atomicLong.longValue() % routingRatio == 0) {
                return true;
            } else if (StringUtils.isEmpty(gray)){
                atomicLong.incrementAndGet();
                map.put(appName.toLowerCase(), atomicLong);
                return true;
            }
        } else {
            map.put(appName.toLowerCase(), new AtomicLong(0));
        }

        return false;
    }

}